package com.wzy.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtHelper {

    @Value("${jwtHelper.key}")
    private String key;
    //创建jwt令牌解析jwt令牌
    @Value("${jwtHelper.validTime}")
    private Integer time;//单位小时

    //根据传过来的id
    public String createJwt(Integer id){
        Map<String ,Object> claims = new HashMap<>();
        claims.put("id",id);
//        claims.put("value",value);
        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256,key)//签名算法
                .setClaims(claims)//自定义内容(载荷)
                .setExpiration(new Date(System.currentTimeMillis() + time*3600*1000))//设置有效期为1*time h
                .compact();
        return jwt;
    }

    public Boolean parseJwt(String jwt){
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(jwt)
                    .getBody();
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
